<template>
  <div :class="['tr-radiogroup-big','no-outline', styles.module]" ref="radioGroup" >
  <LabelPrefixWraper
    v-show="mappingProps.visible"
    :class="['tr-radio-group','no-outline', styles.module]"
    :required="mappingProps.required"
    :label="mappingProps.label"
    :hideLabel="mappingProps.hideLabel"
    :labelPosition="mappingProps.labelPosition"
    :helpConf="mappingProps.helpConf"
    :helpTooltip="mappingProps.helpTooltip"
    :helpPlacement="mappingProps.helpPlacement"
    :helpMore="mappingProps.helpMore"
    :helpMorePopup="mappingProps.helpMorePopup"
    :helpMoreLink="mappingProps.helpMoreLink"
    :helpMoreLinkHrefStatic="mappingProps.helpMoreLinkHrefStatic"
    :helpMoreLinkHrefExp="mappingProps.helpMoreLinkHrefExp"
    :readonly="mappingProps.readonly"
  >
  <div style="width: 100%;flex: 1;position: relative;">
   <div class="tr-radio-group-div">
        <Component
      v-bind="{ ...attrs_, ...mappingProps }"
      :class="['tr-radio-group-small','no-outline', styles.module]"
      :disable="mappingProps.readonly"
      :label="undefined"
      :size="mappingProps.size"
      @update:model-value="showChannel()"
      :options="
        mappingProps.itemsDataSourceType === ''
          ? mappingProps.options
          : mappingProps.itemsDataSourceType === 'static'
            ? computedStaticItems(mappingProps.staticItems)
            : dynamicList(mappingProps.listDataSource)
      "
      v-model="mappingProps.modelValue"
      :tabindex="mappingProps.tabindex?mappingProps.tabindex:0"
      tabindex="-1"
    >
      <template v-for="(v, k, a) in $slots" v-slot:[k]>
        <slot :name="k" />
      </template>
    </Component>
     <div :class="{'message-radio-bg':displayedRequiredError,'tr-radio-group-div-bg':true}" style="height: 1px"></div>
    </div>
   <div v-if="displayedRequiredError" class="u-error-message">
          {{ mappingProps.requiredMessage }}
          </div>
    </div>


  </LabelPrefixWraper>

  </div>
</template>

<script>
import Component from '@teld/q-components/OptionGroup';
import useMappingProps from 't/common/hooks/useMappingProps';
import { commonProps, createNameSpace } from 't/common/utils';
import { defineComponent, computed, ref, watchEffect, onMounted } from 'vue';
import LabelPrefixWraper from '../label-prefix-wraper';
import styles from './index.module.scss';
import './index.scss';
import { useI18n } from 'vue-i18n';
// 钩子方法
import { useFormChild } from '@teld/q-components';
import label from '../label';

  export default defineComponent({
    name: createNameSpace('radio-group'),
    components: { Component, LabelPrefixWraper },
    props: {
      ...commonProps,
      ...Component.props,
      ...LabelPrefixWraper.props,
      readonly: Boolean,
      size: {
        type: String,
        default() {
          return 'xs';
        },
      },
      itemsDataSourceType: {
        type: String,
        default() {
          return '';
        },
      },
            required: {
  			type: Boolean,
  			default() {
  				return false;
  			},
  		},
  		requiredMessage: {
  			type: String,
  			default() {
  				return '必填不能为空';
  			},
  		},
      staticItems: Array,
      listDataSource: Array,
      displayField: String,
      valueField: String,
      mockValue:{
        type: String,
  			default() {
  				return '';
  			},
      }
    },

    emits: ['change'],
    setup(props, { attrs, emit, expose, slots }) {
      const { t } = useI18n({ useScope: 'global' });
       let attrs_ = {...attrs};
      delete attrs_['data-uid'];
      delete attrs_['data-tag'];
      delete attrs_['class'];
      delete attrs_['style'];
      const [mappingProps, mappingExpose] = useMappingProps(props);
      expose({ ...mappingExpose, validate });

      const computedStaticItems = list => {
        if (list) {
          return list.map(item => {
            return { ...item, label: t(item.ValueInfo_label || "", item.label) }
          })
        }
      };
      const dynamicList = list => {
         if (!!window['fas']?.inDesign) {
          return mappingProps.mockValue && typeof mappingProps.mockValue == 'string'?JSON.parse(mappingProps.mockValue):[
              { ID:'.fasr_radiogroup.StaticItems.Item1',label: '静态数据1', value: 1,ValueInfo_label:"Schema.Controls.fasr_radiogroup.StaticItems.Item1.label" },
              { ID:'.fasr_radiogroup.StaticItems.Item2',label: "静态数据2", value: 2,ValueInfo_label:"Schema.Controls.fasr_radiogroup.StaticItems.Item2.label" }
          ];
         } else {
          if (!(list instanceof Array))
            return [
              {
                [mappingProps.displayField]: '动态数据源',
                [mappingProps.valueField]: '',
              },
            ];
          if (list.length == 0) {
            list = [
              {
                [mappingProps.displayField]: '动态数据源',
                [mappingProps.valueField]: '',
              },
            ];
          }
          return list.map(item => {
            const obj = {
              label: item[mappingProps.displayField],
              value: item[mappingProps.valueField],
            };
            return { ...item, ...obj };
          });
        }

      };
      function showChannel() {
        emit('change');
      };
    // ============================= 必填校验相关 ===========================
    // 是否显示必填校验错误
      const displayedRequiredError = ref(false);
      const radioGroup = ref(null)
      onMounted(() => {

      radioGroup.value.tabIndex = -1
    });
    // 必填校验
    function validate() {
    debugger
  	const { required, modelValue, requiredMessage } = mappingProps;
  	const value = modelValue;
  	displayedRequiredError.value = required && (typeof value == 'undefined' || value == null )
  	return !displayedRequiredError.value
      };
    // 与qForm组件通信，校验用户输入是否合法
   useFormChild({
  	validate, // 函数；可以是异步的；
  	// 应该返回一个布尔值（或一个 resolve 布尔值的 Promise）
  	resetValidation() {
  		displayedRequiredError.value = false;
  	},    // 可选的函数，可重置验证
  	requiresQForm: false // 如果没有找到父级 QForm，它是否应该报错？
  });
    // 评分改变回调
      watchEffect(() => {
        // const value = mappingProps.modelValue;
        // emit('update:modelValue', value)
        // 如果已经报了必填错误，更改时校验下
        if (displayedRequiredError.value) validate();
      });

      return { attrs_, styles, mappingProps, showChannel, dynamicList,computedStaticItems,validate,displayedRequiredError, radioGroup };
    },
  });
</script>

<style lang="scss" >
.tr-radio-group{
        // 错误提示样式和input组件保持一致
      .u-error-message {
        font-size: 12px;
        line-height: 1.5;
        padding-top: 5px;
        color:#FF0000;
        word-break: break-word;
        word-wrap: break-word;
        overflow-wrap: break-word;
      }

}

@media only screen and (max-width: 767px) {
 .message-radio-bg{
        background-color: #FF5A66 !important;
      }
}
</style>
